package com.starblink.mine.personhome.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.cache.normalized.FetchPolicy
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.basic.log.SKLogger
import com.starblink.rocketreserver.BlockAccountMutation
import com.starblink.rocketreserver.FetchAccountDataCountByIdQuery
import com.starblink.rocketreserver.FetchAccountDataCountByIdQuery.FetchAccountDataCountById
import com.starblink.rocketreserver.FetchAccountInfoByIdQuery
import com.starblink.rocketreserver.fragment.AccountF
import kotlinx.coroutines.*

class PersonHomeVM : BaseViewModel() {
    var pageType: Int = MineManager.PersonHomePageType.MINE
    var accountId: String = ""

    // 用户基本数据
    val userInfoLiveData: MutableLiveData<AccountF> =
        MutableLiveData()

    // 用户数量数据
    val userCountDataLiveData: MutableLiveData<FetchAccountDataCountById> =
        MutableLiveData()

    val blockUserLiveData: MutableLiveData<Boolean> = MutableLiveData()

    /**
     * 获取用户数据
     * @note 主态-只需获取数量信息
     * 客态-获取用户信息+数量信息
     */
    fun getUserInfo() {
        viewModelScope.launch {
            var accountDeleted = false
            // 仅当页面是客态时，加载其用户信息（主态时，我的用户信息已存在）
            if (pageType == MineManager.PersonHomePageType.OTHER_USER) {
                val response = SkGqlClient.skQuery(
                    FetchAccountInfoByIdQuery(
                        accountId = accountId
                    ),
                    fetchPolicy = FetchPolicy.NetworkFirst
                )
                if (response?.data != null && response.data!!.fetchAccountInfoById != null) {
                    userInfoLiveData.postValue(response.data!!.fetchAccountInfoById!!.accountF)
                    accountDeleted =
                        response.data!!.fetchAccountInfoById!!.accountF.deleted ?: false
                } else {
                    loadError(null)  // 加载失败，显示错误页面
                }
            }

            // 获取用户数量信息, 当客态并且账户已删除时无需加载数量信息
            if (!accountDeleted) {
                getUserCountInfo()
            }
        }
    }

    var getUserCountInfoJob: Job? = null

    /**
     * 获取用户数量信息
     */
    fun getUserCountInfo() {
        viewModelScope.launch {
            if (getUserCountInfoJob != null && getUserCountInfoJob!!.isActive) {
                SKLogger.e("dss", "有新的请求，取消旧请求")
                getUserCountInfoJob!!.cancel()
                getUserCountInfoJob = null
            }
            getUserCountInfoJob = launch {
                val response = SkGqlClient.skQuery(
                    FetchAccountDataCountByIdQuery(
                        accountId = accountId
                    ),
                    fetchPolicy = FetchPolicy.NetworkFirst
                )
                if (response?.data != null && isActive) {
//                    SKLogger.e("dss", "getUserCountInfo成功")
                    //collectionAllCount:收藏、心愿单内容总个数;wishListCount:心愿单数量;collectionCount:收藏数量;
                    //likedCount:被点赞数;postCount:发布内容数,likeCount:我喜欢的内容数
                    userCountDataLiveData.postValue(response.data!!.fetchAccountDataCountById)
                }
            }
        }
    }

    /**
     * 拉黑指定用户
     */
    fun blockUser(accountF: AccountF) {
        if (accountF.blockFlag == true) {
            toast(com.starblink.basic.style.R.string.have_block)
            return
        }
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                BlockAccountMutation(
                    accountId = accountF.id
                ),
                showDefaultLoading = true
            )
            if (response?.data?.blockAccount == true) {
                // 拉黑成功
                blockUserLiveData.postValue(true)
            }
        }
    }
}